<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '资讯详情',
  },
}
</route>

<script lang="ts" setup>
import type { ScrollViewOnScrollEvent } from '@uni-helper/uni-types/index'
import type { CreateGuideDto } from '@/service/app'
import { debounce } from 'lodash'
import { BASE_URL } from '@/constants'
import { guideControllerFindOne as getGuide, guideControllerToggleLike as toggleLike } from '@/service/app'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const userInfo = computed(() => {
  const storeInfo = userStore.userInfo
  return {
    id: storeInfo.id || null,
  }
})

// 定义 detail 并初始化
const detail = ref<{
  /** 攻略id */
  id: number
  /** 攻略标题 */
  title: string
  /** 攻略详情图 */
  detail: string
  /** 攻略封面图 */
  cover: string
  /** 攻略顶图 */
  banner: string
  /** 攻略点赞数 */
  likes: number
  /** 攻略点赞状态 */
  isLiked: boolean
}>()

// 使用 async/await 处理异步操作
onLoad(async (query) => {
  console.log('query:', query)
  try {
    const data = await getGuide({
      params: {
        id: query.id,
        userId: userInfo.value.id,
      },
    })
    detail.value = data?.data
    console.log(detail.value)
  }
  catch (error) {
    console.error('获取攻略详情失败:', error)
  }
})

// 控制导航条显示状态
const showNav = ref(false)
// 处理滚动事件
const scrollTop = ref(0)

function back() {
  uni.navigateBack()
}

const handleScroll = debounce((e: ScrollViewOnScrollEvent) => {
  scrollTop.value = e.detail.scrollTop
  // console.log(e.detail.scrollTop)
}, 30)

// #ifdef MP-WEIXIN
// 微信小程序使用新的API
const systemInfo = uni.getWindowInfo()
const top = systemInfo.safeArea?.top ?? null
// #endif

const backImg = 'https://m.360buyimg.com/i/jfs/t1/287170/5/14892/176740/686777b6F515facd1/f96ff12c4b26b84e.jpg'

// 切换点赞状态
async function handleLike() {
  const data = await toggleLike({
    body: {
      guideId: detail.value?.id,
      userId: userInfo.value.id,
    },
  })
  // console.log(data)
  if (data.success) {
    uni.showToast({
      title: data.message,
      icon: 'none',
    })
    detail.value.isLiked = !detail.value.isLiked
    if (detail.value.isLiked) {
      detail.value.likes++
    }
    else {
      detail.value.likes--
    }
  }
}

// 仅用于非微信小程序平台
function onShare() {
  // #ifdef APP-PLUS
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    title: detail.value?.title || '线路介绍',
    path: `/pages/news/newsDetail?id=${detail.value?.id}`,
    imageUrl: detail.value?.cover || '',
    success: () => {
      console.log('分享成功')
    },
    fail: (err) => {
      console.error('分享失败', err)
    },
  })
  // #endif
}

// 微信小程序分享给朋友钩子
function onShareAppMessage() {
  return {
    title: detail.value?.title || '线路介绍',
    path: `/pages/news/newsDetail?id=${detail.value?.id}`,
    imageUrl: BASE_URL + detail.value?.cover,
    success: (res) => {
      console.log('分享成功', res)
    },
    fail: (err) => {
      console.error('分享失败', err)
    },
  }
}

// 添加分享到朋友圈的钩子
function onShareTimeline() {
  return {
    title: detail.value?.title || '线路介绍',
    query: `id=${detail.value?.id}`,
    imageUrl: BASE_URL + detail.value?.cover,
  }
}
</script>

<!-- 规格选择 -->

<template>
  <!-- 导航栏 -->
  <div
    class="fixed left-0 right-0 z-20 bg-white transition-all duration-300"
    :class="{
      'shadow-md translate-y-0': scrollTop > 50 + top, // 显示状态：阴影+正常位置
      'shadow-none -translate-y-full': scrollTop <= 50 + top, // 隐藏状态：无阴影+上移隐藏
    }"
    :style="{
      top: scrollTop > 50 + top ? 0 : `${-50}px`, // 显示时top为0，隐藏时上移50px
      paddingTop: `${top}px`, // 顶部内边距适配安全区域（避免被状态栏遮挡）
    }"
  >
    <div class="h-11 flex items-center bg-white px-4">
      <wd-icon name="thin-arrow-left" size="22px" @click="back" />
      <h1 class="flex-1 truncate px-6 text-lg text-gray-800 font-medium">
        {{ detail?.title || '线路介绍' }}
      </h1>
    </div>
  </div>

  <scroll-view class="h-300 bg-[#f4f4f4]" scroll-y @scroll="handleScroll">
    <!-- 内容区域，确保内容足够长以触发滚动 -->
    <!-- 背景图 -->
    <image class="h-60 w-100" :src="BASE_URL + detail?.banner" mode="aspectFill" />
    <!-- 头部区域 -->
    <view class="relative z-5 mt-[-65rpx] rounded-tl-2xl rounded-tr-2xl bg-white pb-20 pt-4">
      <view class="flex flex-col px-4">
        <view class="mb-2 text-lg text-gray-800">
          线路介绍
        </view>
        <!-- <img src="https://m.360buyimg.com/i/jfs/t1/288574/20/16285/358915/6868e810F75fcfe87/36bab8b231f6c874.jpg" alt="详情图"> -->
        <image
          class="mx-auto w-full" mode="widthFix"
          :src="BASE_URL + detail?.detail"
        />
        <!-- 内容长度过小会导致无滚动判定，先放两份图片，有长图记得删除 -->
        <image
          class="mx-auto w-full" mode="widthFix"
          :src="BASE_URL + detail?.detail"
        />
      </view>
    </view>
    <!-- 底部功能区 -->
    <view class="h-18" />
    <view
      class="fixed bottom-0 z-6 box-border h-20 w-100% flex items-center justify-evenly rounded-tl-2xl rounded-tr-2xl bg-white py-3"
      style="box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.1);"
    >
      <!-- 分享按钮 -->
      <button open-type="share" class="share-button">
        <view class="flex items-center">
          <wd-icon name="share" size="44rpx" />
          <text class="ml-1">
            分享
          </text>
        </view>
      </button>
      <!-- 点赞按钮 -->
      <view class="ml-5 flex items-center justify-center" @click="handleLike">
        <wd-icon :name="detail?.isLiked ? 'heart-filled' : 'heart'" size="44rpx" :color="detail?.isLiked ? 'red' : 'gray'" />

        <text class="ml-1">
          {{ detail?.likes }}
        </text>
      </view>
      <!-- <view
        class="h-70% w-30% flex items-center justify-center rounded-lg bg-[linear-gradient(to_right,#e0cebd,#bfa189)] from-[#f8f0eb] to-[#e7d3c3] text-white"
      >
        确定
      </view> -->
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-bar {
  height: var(--status-bar-height);
  width: 100%;
}

.share-button {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  line-height: normal;
  outline: none;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.share-button::after {
  border: none;
}
</style>
